from apps.project.business.zentao import ZenTaoBusiness
from apps.project.business.zentao_son import ZenTaoCase
from apps.interface.business.interfaceapimsg import InterfaceApiMsgBusiness
from apps.project.middle.zt_case import CaseData
from apps.project.middle.type import ZenTao
from flask import current_app, g
from library.trpc import Trpc
from multiprocessing import Process


class TestCaseBusiness(object):
    user_trpc = Trpc('auth')
    public_trpc = Trpc('public')
    
    @classmethod
    def check_case_content(cls, file, import_type):
        """校验用例导入内容
        :param file: 文件内容
        :param import_type: 导入类型
        :return: 用例内容
        """
        try:
            file_suffix = cls.judge_file_suffix(file)
            # 文件路径
            path = InterfaceApiMsgBusiness.case_file_upload(file).get('data')
            # 目前支持禅道，后续支持扩展
            data, msg = ZenTao(import_type, path, file_suffix).check_case_type()
            msg_data, code = cls.page_data(data.zt_case, msg, data.title, path, import_type)
            return '成功', msg_data, code
        except Exception as e:
            current_app.logger.error(str(e))
            return str(e), '', 500
    
    @classmethod
    def page_data(cls, data, msg, title, path, import_type):
        """前端页面展示数据
        :param data:
        :param msg:
        :param title:
        :param path:
        :param import_type:
        :return:
        """
        if msg != '成功':
            return msg, 400
        content = [{'module': d.get('module'),
                    'case_title': d.get('title'),
                    'pri': d.get('pri'),
                    'precondition': d.get('precondition')} for d in data]
        msg_data = {'content': content, 'title': title,
                    "path": '{}{}#import_type{}'.format(g.userid, path, import_type)}
        return msg_data, 200
    
    @classmethod
    def import_case(cls, path, import_type):
        """导入用例
        :param path:
        :param import_type:
        :return:
        """
        try:
            data = CaseData.g_case_list
            case_data = CaseData.if_exist_cases(data, path)
            if not case_data:
                return '用例内容不存在,导入失败,请重新导入', '', 400
            # 获取禅道添加用例前置数据
            zt_data = ZenTaoBusiness.get_zt_case_add_front_data(import_type,
                                                                data[0].get('lid'))
            # 用例库导入
            if import_type == '1':
                for index, case in enumerate(case_data, 1):
                    print('num:{} 用例标题:{}'.format(index, case.get('title')))
                    ZenTaoBusiness.new_zt_case_sync(data[0].get('r_session'), case, zt_data)
            elif import_type == '2':
                for index, case in enumerate(case_data, 1):
                    print('num:{} 用例标题:{}'.format(index, case.get('title')))
                    ZenTaoCase.new_zt_case_sync(data[0].get('r_session'), case, zt_data)
            else:
                pass
            # p = Process(target=CaseData.sync_zt_case,
            #             args=(case_data.get('r_session'), case_data.get(path), lid),
            #             daemon=True)
            # print(p.is_alive())
            # p.is_alive()
            # p.start()
            # p.join()
            
            # 开启一个进程去禅道入库-先不做
            # task_id = parse_pwd(path)
            # r_session = case_data.get('r_session')
            # case_status = CaseData.import_record(task_id, path)
            # if not case_status:
            #     return '已有用例正在导入，请稍后再试', '', 400
            # print("当前进程ID：", os.getpid())
            # p = Process(target=CaseData.sync_zt_case,
            #             args=(case_data.get(path), lid, r_session, task_id,),
            #             daemon=True)
            # print(p.is_alive())
            # p.is_alive()
            # p.start()
            return '用例导入成功,请去禅道查收', '', 200
        except Exception as e:
            current_app.logger.error(str(e))
        finally:
            del CaseData.g_case_list[:]
        return str(e), '', 500
    
    @classmethod
    def judge_file_suffix(cls, file):
        """判断文件类型
        :param file:文件
        :return:
        """
        # 取最后一个 如：需求v2.1.0.xmind
        file_suffix = file.filename.split('.')[-1]
        if file_suffix not in ['xmind']:
            raise Exception('请选择xmind文件导入')
        return file_suffix
